package cn.lbz.page;

import cn.lbz.Food.Init.DBUtils;
import cn.lbz.Food.Init.DBfood;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.Serial;
import java.io.Writer;
import java.sql.SQLException;
import java.util.List;

public class RecommendServlet extends HttpServlet {
    @Serial
    private static final long serialVersionUID = -559649991163918599L;
    public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
        this.doPost(request, response);}
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws IOException, ServletException {
        String type = request.getParameter("type");
        String sql = "SELECT * FROM share_food where type=\""+ type +"\"";
        System.out.println(sql);
        try {
            List<DBfood> foodbytype = DBUtils.getfood(sql);
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            try(Writer writer = response.getWriter()) {
                writer.write(this.toJson(foodbytype));
                System.out.println(this.toJson(foodbytype));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    private String toJson(List<DBfood> foodbytype){
        StringBuilder ft = new StringBuilder();
        ft.append("{");
        ft.append("\"food\":[");
        for (int i=0;i<foodbytype.size();i++){
            DBfood dBfood = foodbytype.get(i);
            if (i > 0) ft.append(",");
            ft.append(String.format(
            "{\"id\": %s, \"name\": \"%s\",\"located\": \"%s\",\"price\": %s,\"type\": \"%s\",\"reason\": \"%s\",\"pics\": \"%s\"}",
                    dBfood.getId(),dBfood.getName(),dBfood.getLocated(),
                    dBfood.getPrice(),dBfood.getType(),dBfood.getreason(),dBfood.getPics()));
        }
        ft.append("]");
        ft.append("}");
        return ft.toString();
    }
}
